package com.example.tabbar.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.adapter.RoleAdapter
import com.example.tabbar.databinding.FragmentRoleListBinding
import com.example.tabbar.listener.OnFragmentSwitchListener
import com.example.tabbar.utils.CustomLine
import com.junray.usermangement.room.entity.Permission
import com.junray.usermangement.room.entity.Role
import com.junray.usermangement.utils.LiveDataUtils.observeOnce
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.viewModel.UserViewModel
import java.util.concurrent.atomic.AtomicInteger


class RoleListFragment : Fragment() {
    private var binding: FragmentRoleListBinding? = null
    private var recyclerview: RecyclerView? = null
    private var adapter: RoleAdapter? = null
    private var viewmodel: UserViewModel? = null
    private var sessionManager: SessionManager? = null
    private var currentList: List<Permission>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }
    private var listener : OnFragmentSwitchListener? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentRoleListBinding.inflate(inflater, container, false)
        return binding ?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        //用户列表底部按钮
        onClick()
    }

    private fun initView() {
        sessionManager = SessionManager.instance
        viewmodel = ViewModelProvider(this)[(UserViewModel::class.java)]
        recyclerview = binding?.usersRecyclerView
        adapter = RoleAdapter()
        recyclerview?.adapter = adapter
        recyclerview?.layoutManager = LinearLayoutManager(requireContext())

        //分割线
        CustomLine(requireContext(),recyclerview!!)

        adapter?.setOnItemClickListener { item,name ->
            val editUserFragment = EditRoleFragment.newInstance(item.id,name,item.level)
            listener?.onFragmentSwitch(editUserFragment)
        }

        // 先观察当前用户的权限
        val currentUserId = sessionManager!!.roleId
        val currentUserLevel = sessionManager?.currentRoleLevel ?: 4 // 默认操作员级别
        if (currentUserId == 0L) {
            // 如果当前用户角色ID为0，不执行后续逻辑
            adapter?.setItems(ArrayList())
            return
        }

        viewmodel!!.allRoles!!.observe(
            viewLifecycleOwner
        ) { roles: MutableList<Role>? ->
            if (!roles.isNullOrEmpty()) {
                filterRolesByLevelAndPermissions(roles, currentUserLevel)
            } else {
                adapter!!.setItems(ArrayList())
            }
        }

    }
    private fun filterRolesByLevelAndPermissions(
        roles: MutableList<Role>,
        currentUserLevel: Int
    ) {
        val filteredRoles: MutableList<Role> = ArrayList()
        if (sessionManager!!.isSuperAdmin) {
            adapter!!.setItems(roles)
            return
        }

        // 过滤掉同级别和高级别的角色
        val levelFilteredRoles = roles.filter { role ->
//                    || (role.level == currentUserLevel && role.id == sessionManager!!.roleId)  // 同级别只显示自身
            role.level > currentUserLevel
        }

        if (levelFilteredRoles.isEmpty()) {
            adapter!!.setItems(ArrayList())
            return
        }

        for (role in levelFilteredRoles) {
            filteredRoles.add(role)
            val distinctRoles = filteredRoles.distinctBy { it.id }.sortedBy { it.id }
            adapter!!.setItems(distinctRoles)
        }
    }
    private fun onClick() {

    }


    fun setListener(listener: OnFragmentSwitchListener) {
        this.listener = listener
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            RoleListFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}